#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <getopt.h>

#include <linux/input.h>
#include <sys/ioctl.h>
#include <tslib.h>

#include "gesture.h"
#include "track.h"

static struct tsdev *ts;
static struct ts_sample_mt **samp_mt;
static int max_slots;


// 初始化触摸屏需要的内存，若成功，则返回触摸屏支持的最大触点数
int init_touch_screen()
{
    int ret;
    struct input_absinfo slot;

    ts = ts_setup(NULL,0);
    if(!ts)
    {
        printf("ts_setup err!\n");
        return -1;
    }

     //通过以下代码寻找触摸屏的最大slot信息
     if (ioctl(ts_fd(ts), EVIOCGABS(ABS_MT_SLOT), &slot) < 0) {
		perror("ioctl EVIOGABS");
		ts_close(ts);
		return -1;
	}

	max_slots = slot.maximum + 1 - slot.minimum;    //获得屏幕支持的最多触点的数据   
    printf("max_slots = %d\n",max_slots);

    samp_mt = malloc(sizeof(struct ts_sample_mt *));
    if (!samp_mt) {
		ts_close(ts);
		return -1;
	}

    samp_mt[0] = calloc(max_slots,sizeof(struct ts_sample_mt));
    if(samp_mt[0] == NULL)
    {
        free(samp_mt);
        ts_close(ts);
		return -1;
    }

    ret = init_touch_points(max_slots);
    if(ret < 0)
    {
        printf("init touch points failed!\n");
        return -1;
    }

    return 0;
}

GestureType get_gesture_type()
{
    int ret;
    
    ret = ts_read_mt(ts,samp_mt,max_slots,1);
    if(ret < 0)
    {
        printf("ts_read_mt error!\n");
        return GESTURE_ERROR;
    }

    return proc_gesture(samp_mt);
}


void exit_touch_screen()
{
    if(ts)
    {
        exit_touch_points();
        free(samp_mt[0]);
        free(samp_mt);
        ts_close(ts);
    }
}